package com.mk.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mk.base.exception.ApplicationException;
import com.mk.base.exception.StatusCode;
import com.mk.base.service.impl.BaseService;
import com.mk.mapper.RoleResourceMapper;
import com.mk.model.entity.RoleResource;
import com.mk.service.IRoleResourceService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yq
 * @Description:
 * @Date: Created in 4:30 PM 3/13/18
 */
@Service
public class RoleResourceService extends BaseService<RoleResourceMapper,RoleResource> implements IRoleResourceService {

    @Override
    public List<RoleResource> getByResourceId(Long resourceId) {
        return super.selectList(new EntityWrapper<RoleResource>().eq("resource_id",resourceId));
    }

    @Override
    public Boolean changeRolePermissions(Long roleId, List<Long> resourceIds) {
        if(roleId == null)
            throw new ApplicationException(StatusCode.BAD_REQUEST.getCode(),"请选择需要编辑的角色及编辑后的资源信息");
        super.delete(new EntityWrapper<RoleResource>().eq("role_id",roleId));
        if(!CollectionUtils.isEmpty(resourceIds)){
            List<RoleResource> roleResources = new ArrayList<>();
            for (Long resourceId : resourceIds) {
                RoleResource resource = new RoleResource();
                resource.setRoleId(roleId);
                resource.setResourceId(resourceId);
                roleResources.add(resource);
            }
            return super.insertBatch(roleResources);
        }
        return Boolean.TRUE;
    }
}
